package com.liruo.learn.spring.mvc.controller.mvc;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author:liruo
 * @Date:2023-05-30-21:27:54
 * @Desc
 */
@Slf4j
@RestController
@RequestMapping("/redirect-forward")
public class RedirectOrForwardController {
    @GetMapping("/doRedirect")
    public void doRedirect(@RequestParam("code")String code, HttpServletResponse resp){
        //localhost:7100/redirect-forward/doRedirect?code=123
        log.info("doRedirect, code={}", code);
        try {
            resp.sendRedirect("/redirect-forward/redirectTarget?code=" + code);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    @GetMapping("/redirectTarget")
    public void redirectTarget(@RequestParam("code")String code, HttpServletRequest req){
        log.info("redirectTarget, code={}", code);
    }

    @GetMapping("/doForward")
    public void doForward(@RequestParam("code")String code, HttpServletRequest req, HttpServletResponse resp){
        log.info("doForward, code={}", code);
        try {
            req.getRequestDispatcher("/redirect-forward/forwardTarget").forward(req, resp);
        } catch (IOException | ServletException e) {
            throw new RuntimeException(e);
        }
    }
    @GetMapping("/forwardTarget")
    public void forwardTarget(@RequestParam("code") String code, HttpServletRequest req){
        log.info("redirectTarget, code={}", code);
    }

}
